<template>
  <view class="container">
    <uni-forms :model="form">
      <uni-forms-item label="路由路径">
        <uni-easyinput v-model="form.path" placeholder="如: pages/crm/index" />
      </uni-forms-item>
      <uni-forms-item label="页面标题">
        <uni-easyinput v-model="form.style.navigationBarTitleText" placeholder="页面标题" />
      </uni-forms-item>
      <uni-forms-item label="访问权限">
        <uni-data-checkbox 
          v-model="form.permissions"
          :localdata="roles"
          multiple
        />
      </uni-forms-item>
      <button type="primary" @click="saveRoute">保存</button>
    </uni-forms>
  </view>
</template>

<script>
import routesData from '@/api/routes.json'

export default {
  data() {
    return {
      form: {
        path: '',
        style: {
          navigationBarTitleText: ''
        },
        permissions: []
      },
      roles: [
        { value: 'admin', text: '管理员' },
        { value: 'user', text: '普通用户' }
      ]
    }
  },
  onLoad(options) {
    if (options.path) {
      const route = routesData.routes.find(r => r.path === options.path)
      if (route) {
        this.form = JSON.parse(JSON.stringify(route))
      }
    }
  },
  methods: {
    async saveRoute() {
      try {
        const routes = routesData.routes
        const index = routes.findIndex(r => r.path === this.form.path)
        
        if (index >= 0) {
          // 更新现有路由
          routes[index] = this.form
        } else {
          // 添加新路由
          routes.push(this.form)
        }
        
        // 保存到本地文件
        await this.saveRoutesToFile(routes)
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        uni.navigateBack()
      } catch (e) {
        uni.showToast({
          title: '保存失败',
          icon: 'error'
        })
        console.error(e)
      }
    },
    saveRoutesToFile(routes) {
      return new Promise((resolve, reject) => {
        // 实际项目中需要通过后端API保存
        // 这里模拟保存到本地
        routesData.routes = routes
        resolve()
      })
    }
    }
  }
}
</script>